/*
 * @Author: Weixiang
 * @Date: 2022-07-04 17:56:47
 * @LastEditors: Weixiang
 * @LastEditTime: 2022-07-11 16:12:33
 * @Description: 存储项目运行信息
 */

/*
 *    getSystemTimelog  获取对象
 *    setInfo(key, value)   设置相关信息
 *    setTime(type, value)  设置时间戳 value为空取当前时间
 *    sendValue(api)    发送数据
 */
import fecha from 'fecha';

let systemTimelog;

class SystemTimelog {
    constructor(eventType) {
        this.timeObj = {};
        this.infoObj = {
            eventType: eventType,
            userTrace: null
        };
    }

    setTime = (type, value) => {
        this.timeObj[type] = value || Date.now();
    }

    setInfo = (key, value) => {
        this.infoObj[key] = value;
    }

    sendValue = (api) => {
        this.timeObj.pageStart ||= window.pageStart;
        //输出转译后时间
        let showObj = {};
        for (let key in this.timeObj) {
            showObj[key] = this.timeObj[key] && fecha.format(this.timeObj[key], 'YYYY-MM-dd HH:mm:ss');
        }
        console.log({ ...this.infoObj, ...showObj });
        //发送请求
        api?.({
            ...this.infoObj,
            ...this.timeObj
        });
        //清空数据
        delete window.pageStart;
        systemTimelog = null;
    }
}

const getSystemTimelog = (eventType) => {
    if (!systemTimelog) systemTimelog = new SystemTimelog(eventType || 'SSO');
    return systemTimelog;
};

export default getSystemTimelog;